<?php
function get_real_ip() {
    $ip_keys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'];
    
    foreach ($ip_keys as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = $_SERVER[$key];
            if (strpos($ip, ',') !== false) {
                // 处理多个IP的情况，取第一个
                $ips = explode(',', $ip);
                $ip = trim($ips[0]);
            }
            
            // 验证IP格式
            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                return $ip;
            }
        }
    }
    
    return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}

function save_log($data) {
    $log_file = __DIR__ . '/logs_' . date('Y-m-d') . '.json';
    $real_ip = get_real_ip();
    
    $log_entry = [
        'ts' => date('Y-m-d H:i:s'),
        'ip_real' => $real_ip, // 真实IP地址
        'ip_anonymized' => $data['ip_anonymized'], // 匿名化后的IP
        'ua_hash' => $data['ua_hash'],
        'ua_raw' => $data['ua_raw'],
        'ref_hash' => $data['ref_hash'],
        'path' => $data['path'],
        'method' => $data['method'],
        'lang' => $data['lang'],
        'consent' => $data['consent'],
        'gps_lat' => $data['gps_lat'],
        'gps_lng' => $data['gps_lng'],
        'gps_accuracy' => $data['gps_acc']
    ];
    
    $logs = [];
    if (file_exists($log_file)) {
        $logs = json_decode(file_get_contents($log_file), true) ?: [];
    }
    $logs[] = $log_entry;
    file_put_contents($log_file, json_encode($logs, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

function get_logs($date = null) {
    $log_file = __DIR__ . '/logs_' . ($date ?: date('Y-m-d')) . '.json';
    return file_exists($log_file) ? json_decode(file_get_contents($log_file), true) ?: [] : [];
}
?>